package edu.nf.llmtest.service.factory;

import edu.nf.llmtest.common.annotation.MessageType;
import edu.nf.llmtest.service.Handler.MessageHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ Author bin
 * @ Create  2025/10/27 上午10:49
 **/
@Service
@Slf4j
public class HandlerFactory implements ApplicationContextAware {

    private final Map<String, MessageHandler> handlerMap = new HashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        Map<String, Object> beans = ctx.getBeansWithAnnotation(MessageType.class);

        for (Object bean : beans.values()) {
            Class<?> targetClass = AopUtils.getTargetClass(bean);
            MessageType type = targetClass.getAnnotation(MessageType.class);

            handlerMap.put(type.value(), (MessageHandler) bean);
        }

        log.info("✅ 已注册消息类型:{} " , handlerMap.keySet());
    }

    public MessageHandler getHandler(String type) {
        return handlerMap.get(type);
    }
}
